package server;

import mapper.MappedContext;
import mapper.MappedWrapper;
import mapper.Mapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, HttpServlet> servletMap;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap, Mapper mapper) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            List<MappedContext> mappedContextList = mapper.getMappedHost().getMappedContextList();

            boolean flag_404 = true;

            for (MappedContext mappedContext :
                    mappedContextList) {

                List<MappedWrapper> wrapperList = mappedContext.getWrapperList();

                for (MappedWrapper mappedWrapper :
                        wrapperList) {
                    String projectPath = "/" + mappedContext.getProjectName();
                    List<String>  strings = Arrays.asList(projectPath, projectPath + "/index.html");
                    // 项目 或者 项目/index.html
                    if (strings.contains(request.getUrl())) {
                        String path = mappedContext.getProjectPath() + "/index.html";
                        response.outputHtml(path);
                        flag_404 = false;
                        // 项目/(servlet key)
                    } else if (request.getUrl().equals(projectPath  + mappedWrapper.getKey())) {
                        // 动态资源servlet请求
                        HttpServlet httpServlet = mappedWrapper.getHttpServlet();
                        httpServlet.service(request, response);
                        flag_404 = false;
                    }
                }
            }
            // 请求地址 都没有 匹配成功
            if (flag_404){
                String content = "<h1>404</h1>";
                response.output((HttpProtocolUtil.getHttpHeader200(content.getBytes().length) + content));
            }

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
